/*
	Copyright (c) 2008, Grant Jones <grant@podtronics.com>.
	All rights reserved.

	Redistribution and use in source and binary forms, with or
	without modification, are permitted provided that the following
	conditions are met:

		Redistributions of source code must retain the above copyright
		notice, this list of conditions and the following disclaimer.
		
		Redistributions in binary form must reproduce the above copyright
		notice, this list of conditions and the following disclaimer in
		the documentation and/or other materials provided with the
		distribution.
		
		Neither the name of the gxjones.com nor the names of its
		contributors may be used to endorse or promote products derived
		from this software without specific prior written permission.
	
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
	LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
	FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
	INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
	STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
	OF THE POSSIBILITY OF SUCH DAMAGE.
	
	http://www.opensource.org/licenses/bsd-license.php
*/

/*
 *  asdb_main.c
 *  scatterd
 *
 *  Created by Grant Jones on 3/12/08.
 *
 */

/*
** This module should provide the following:
** - correctly interface with Amazon SimpleDB providing most of the
**   functionality required
** - "RESTful" HTTP
** - HMAC-SHA1 Message Signatures (provided via OpenSSL)
** - sync a remote domain with the cached local version
** - provide a generic set of interface methods for the rest of the
**   program to use
**
**
** Notes:
** - a domain called <determine global settings domain name> will
**   contain all the settings that determine sync time and temp
**   file locations and such. sync time will be something like:
**   nightly, hourly, or idle (where idle is whenever it gets a 
**   chance to do a sync).
** - asdb requires the expat XML parsing library at this time to
**   parse the server response
** - asdb requires the OpenSSL library to provided HMAC-SHA1 and 
**   base-64 functionality required to make requests to amazon web
**   services.
** - asdb requires the libevent library to provide the HTTP client
**   functionality required to communicate with Amazon SimpleDB
**   servers. 
**
** For future development:
** - distributed consistent data replication of domains (might not be
**   possible to do using only simpledb)
**
**
**
*/

#include "edb_main.h"
#include "edb_net_shell.h"

#include "edb_msg_parser.h"
#include "edb_domain.h"

#include "asdb_request.h"

static int asdb_delete( simpledb_t *sdb, const char *domain, size_t domain_sz )
{
	int was_idle = (sdb->requests->num == 0?1:0);	/* when we started was the worker queue idle? */

	printf("asdb_delete\n");
	asdb_req_queue_domain_delete( sdb, domain, domain_sz ); 
	
	if( sdb->requests->num > 0 && was_idle )
	{
		printf("starting up worker queue\n");
		/* starts handling the first queued request, the response handler will
		** handle the next until the queue is empty */
		asdb_req_do_next( sdb );
	}
	
	return 0;
}

static int asdb_syncdown( simpledb_t *sdb, const char *domain, size_t domain_sz )
{
	int was_idle = (sdb->requests->num == 0?1:0);	/* when we started was the worker queue idle? */

	printf("asdb_syncdown\n");
	asdb_req_queue_getall( sdb, domain, domain_sz ); 
	
	if( sdb->requests->num > 0 && was_idle )
	{
		printf("starting up worker queue\n");
		/* starts handling the first queued request, the response handler will
		** handle the next until the queue is empty */
		asdb_req_do_next( sdb );
	}
	
	return 0;
}


static int asdb_syncup( simpledb_t *sdb, const char *domain, size_t domain_sz )
{
	cmapStruct *r;
	cmapStruct *itemattrs;
	mempool_t tmp_pool;
	edb_net_item_t item;
	edb_net_item_attr_t attrs[2];
	int affect_cnt = 0;
	cmapEnumStruct e;
	CMAP_KEY_TYPE item_cnt;
	int was_idle = (sdb->requests->num == 0?1:0);	/* when we started was the worker queue idle? */
	
	/* can't sync the edbsync domain */
	if( domain_sz == strlen(EDB_SYNC_DOMAIN) && memcmp( domain, EDB_SYNC_DOMAIN, domain_sz ) == 0 )
		return -1;

	
	mempool_init(&tmp_pool, 8192);
	
	item.attr_count = 1;
	item.attrs = attrs;
	
	attrs[0].key = "domain_name";
	attrs[0].value = (char *)domain;
	attrs[0].value_sz = domain_sz;
	
	r = edb_msg_parser( sdb->pcs_ptr, &tmp_pool, "SELECT * FROM edbsync WHERE domain_name = $domain_name;", 1, &item );

	
	if( r->num <= 0 )
		goto finished;

	/* make sure the domain exists */
	asdb_req_queue_domain_create(sdb, domain, domain_sz);

	for( cmap_enum(r, &e); (itemattrs = edb_net_item2strmap( &tmp_pool, cmap_enum_next(&e, &item_cnt) ) ); )
	{
		edb_net_item_attr_t *affected_key_attr = strmap_lookup(itemattrs, "affected_key", 12);
		cmapStruct *r_affected_item;
		cmapStruct *affected_item;
		item.attr_count = 2;

		/* attrs[0] is carried over from earlier */
		attrs[1].key = affected_key_attr->key;
		attrs[1].value = affected_key_attr->value;
		attrs[1].value_sz = affected_key_attr->value_sz;
		
		r_affected_item = edb_msg_parser( sdb->pcs_ptr, &tmp_pool, "SELECT * FROM $domain_name WHERE _name = $affected_key;", 1, &item );
		
		if( r_affected_item->num > 1 )
		{
			/* can only really be one */
			printf("expected only one item, got : %d\n", r_affected_item->num );
			continue;
		}
		
		if( r_affected_item->num == 0 )
		{
			/* the item was delete from the domain */

			// asdb_delete( sdb, domain, domain_sz, affected_key_attr->value, affected_key_attr->value_sz );
		}
		else
		{
			/* the item was modified in some way */
			affected_item = edb_net_item2strmap( &tmp_pool, cmap_lookup( r_affected_item, cmap_gethighestkey(r_affected_item) ) );
			if(!affected_item)
				continue;

			/* we now have the full item in memory, this needs to go up to amazon */
			printf("to store: %d attributes from item\n", affected_item->num );			
			
			
			asdb_queue_store( sdb, domain, domain_sz, affected_item );
		}
		
		
		affect_cnt ++;
	}
	


finished:	
	cmap_destroy(r);	

	mempool_destroy(&tmp_pool);
	
	if( sdb->requests->num > 0 && was_idle )
	{
		printf("starting up worker queue\n");
		
		/* starts handling the first queued request, the response handler will
		** handle the next until the queue is empty */
		asdb_req_do_next( sdb );
	}
	
	return affect_cnt;
}



int asdb_create( simpledb_t *sdb, void *pcs_ptr )
{
	/* do default initailization: */
	asdb_create_nop( sdb, pcs_ptr );
	
	/* environ needs to be setup correctly */
	if( !getenv("AWS_SECRET_KEY") ||
		!getenv("AWS_ACCESS_KEY") )
	{
		fprintf(stderr,"in order to sync with Amazon's SimpleDB AWS_SECRET_KEY and AWS_ACCESS_KEY environment variables must be set.\n");
		return 0;
	}
	
	/* setup the real handler functions: */
	sdb->syncup = asdb_syncup;
	sdb->syncdown = asdb_syncdown;
	sdb->delete = asdb_delete;
//	sdb->getattrs = asdb_getattrs;
	
//	printf("asdb_create\n");
//	asdb_req_test();


	sdb->access_info = cmap_new(&sdb->pool);
	
	strmap_assign(sdb->access_info, ASDB_ACCESS_KEY, ASDB_ACCESS_KEY_SZ,
//						asdb_req_mkval2( access_info->mempool, "01234567890123456789" ) );
						asdb_req_mkval2( &sdb->pool, getenv("AWS_ACCESS_KEY") ) );

	strmap_assign(sdb->access_info, ASDB_SECRET_KEY, ASDB_SECRET_KEY_SZ,
						asdb_req_mkval2( &sdb->pool, getenv("AWS_SECRET_KEY") ) );						
//						asdb_req_mkval2( access_info->mempool, "JjdfhskdjfSLDKFLKLKlksdjflksdkljfsdlklkf" ) );						
	

	
	return 0;
}


/* do nothing handler functions: */
static int asdb_nop_syncup( simpledb_t *sdb, const char *domain, size_t domain_sz ) { return 0; }

int asdb_create_nop( simpledb_t *sdb, void *pcs_ptr )
{
	memset( sdb, 0, sizeof(simpledb_t) );
	
#ifndef WIN32
	mempool_init(&sdb->pool, getpagesize());
#else
	mempool_init(&sdb->pool, 8192);
#endif
	sdb->pcs_ptr = pcs_ptr;
	sdb->requests = cmap_new( &sdb->pool );
	
	sdb->syncup = asdb_nop_syncup;
	sdb->syncdown = asdb_nop_syncup;
	sdb->delete = asdb_nop_syncup;
//	sdb->getattrs = asdb_nop_getattrs;
	
	return 0;
}